// 这里是一段安卓代码，用于调用相册和获取选中的图片路径
// 代码中涉及到权限申请、相册调用和获取图片路径的操作

package com.unity3d.player;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;



import android.app.Activity;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class UnityMainActivity extends UnityPlayerActivity {
    public static final String IMAGE_UNSPECIFIED = "image/*";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        // 获取存储权限，否则无法获取图片
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
        }
    }

    public   void InstallApk(String url,String path) {
        Log.d("unity", url+"_____________"+path);
        Utli.a1();

     Utli.InstallApk( path);

    }



    // Unity点击按钮触发这个方法
    public void startPhoto(int result) {
        Log.d("unity", Build.VERSION.SDK_INT+"打开相册111"+Build.VERSION_CODES.KITKAT);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {

            startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*").putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true),

                    1);


        } else {

            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

            intent.setType("image/*");

            startActivityForResult(intent, 1);

        }
    }


    public void onActivityResult(int requestCode, int resultCode,    Intent data) {
        super.onActivityResult(requestCode,resultCode,data);

        // User has picked an image. Transfer it to group owner i.e peer using
        // FileTransferService.
        Uri uri;
        List<String> fileList = new ArrayList<>();
        String paths;

        if ( data != null) {
            ClipData imageNames = data.getClipData();
            if (imageNames != null) {
                StringBuilder uriString = new StringBuilder();
                for (int i = 0; i < imageNames.getItemCount(); i++) {
                    Uri imageUri = imageNames.getItemAt(i).getUri();
                    fileList.add(imageUri.toString());
                    Log.e("Unity", "图片地址"+imageUri);

                    String realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, imageUri);
                    Log.e("Unity", "图片地址"+ realPathFromUri);
                    uriString.append(realPathFromUri).append(",");

                }
                if (uriString.length() > 0) {
                    uriString.deleteCharAt(uriString.length() - 1);
                }
                UnityPlayer.UnitySendMessage("PhotoManager", "GetPhoto",uriString.toString());
            } else {
                uri = data.getData();
                Log.e("Unity", "图片地址1"+uri);
                ContentResolver resolver = getContentResolver();
                String realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
                Log.e("Unity", "图片地址1"+ realPathFromUri);
                UnityPlayer.UnitySendMessage("PhotoManager", "GetPhoto", realPathFromUri);
                //fileList.add(uri.toString());
            }
        } else {
            uri = data.getData();
            Log.e("Unity", "图片地址2"+uri.getPath());
            UnityPlayer.UnitySendMessage("PhotoManager", "GetPhoto", uri.getPath());
            //fileList.add(uri.toString());
        }
    }

    public String GetManyPath(Intent data) {
        Uri[] imageUris = null;
        if (data.getClipData() != null) {
            int count = data.getClipData().getItemCount();
            imageUris = new Uri[count];
            for (int i = 0; i < count; i++) {
//                imageUris[i] = data.getClipData().getItemAt(i).getUri();
                imageUris[i] = data.getClipData().getItemAt(i).getUri();
            }
        } else if (data.getData() != null) {
            imageUris = new Uri[]{data.getData()};
        }
        if (imageUris != null) {
            StringBuilder uriString = new StringBuilder();

            for (Uri uri : imageUris) {
                String imagePath;
//                Cursor cursor = getContentResolver()
//                        .query(uri, new String[]{MediaStore.Images.ImageColumns.DATA},
//                                null, null, null);
                Cursor cursor = getContentResolver()
                        .query(uri, new String[]{MediaStore.Images.ImageColumns.DATA},
                                null, null, null);
                if (cursor == null) {
                    imagePath = uri.getPath();
                } else {
                    cursor.moveToFirst();
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    Log.e("Unity", "相册返回index"+index);
                    imagePath = cursor.getString(index);
                    cursor.close();
                }
                uriString.append(imagePath).append(",");
            }
            if (uriString.length() > 0) {
                uriString.deleteCharAt(uriString.length() - 1);
            }
            return uriString.toString();
        }
        return null;
    }

    // 让Unity调用的方法
    public void CallAndroid(String Msg) {
        Toast.makeText(UnityMainActivity.this, Msg, Toast.LENGTH_SHORT).show();
    }


    /**
     * 根据Uri获取图片的绝对路径
     *
     * @param context 上下文对象
     * @param uri     图片的Uri
     * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
     */
    public static String getRealPathFromUri(Context context, Uri uri) {

        // Uri分为三个部分   域名://主机名/路径/id
        // content://media/extenral/images/media/17766
        // content://com.android.providers.media.documents/document/image:2706
        // file://com.xxxx.xxxxx ---- 7.0 有限制

        int sdkVersion = Build.VERSION.SDK_INT;
        if (sdkVersion >= 19) { // api >= 19
            return getRealPathFromUriAboveApi19(context, uri);
        } else { // api < 19
            return getRealPathFromUriBelowAPI19(context, uri);
        }
    }

    /**
     * 适配api19以下(不包括api19),根据uri获取图片的绝对路径
     *
     * @param context 上下文对象
     * @param uri     图片的Uri
     * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
     */
    private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            data = getDataColumn(context, uri, null, null);
        }
        return data;
    }

    /**
     * 适配api19及以上,根据uri获取图片的绝对路径
     *
     * @param context 上下文对象
     * @param uri     图片的Uri
     * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
     */
    @SuppressLint("NewApi")
    private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
        String filePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是document类型的 uri, 则通过document id来进行处理
            String documentId = DocumentsContract.getDocumentId(uri);
            if (isMediaDocument(uri)) { // MediaProvider
                final String[] divide = documentId.split(":");
                final String type = divide[0];
                Uri mediaUri = null;
                if ("image".equals(type)) {
                    mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    mediaUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    mediaUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                } else {
                    return null;
                }
                String selection = BaseColumns._ID + "=?";
                String[] selectionArgs = {divide[1]};
                filePath = getDataColumn(context, mediaUri, selection, selectionArgs);
            } else if (isDownloadsDocument(uri)) { // DownloadsProvider
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                filePath = getDataColumn(context, contentUri, null, null);
            }else if(isExternalStorageDocument(uri)) {
                String [] split = documentId.split(":");
                if(split.length >= 2) {
                    String type = split[0];
                    if("primary".equalsIgnoreCase(type)) {
                        filePath = Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                }
            }
        } else if (ContentResolver.SCHEME_CONTENT.equalsIgnoreCase(uri.getScheme())){
            // 如果是 content 类型的 Uri
            filePath = getDataColumn(context, uri, null, null);
        } else if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            // 如果是 file 类型的 Uri,直接获取图片对应的路径
            filePath = uri.getPath();
        }
        return filePath;
    }

    /**
     * 获取数据库表中的 _data 列，即返回Uri对应的文件路径
     * @return
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        String path = null;

        String[] projection = new String[]{MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                path = cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is MediaProvider
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is DownloadsProvider
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
}
